import axios from 'axios'
const root = process.env.REACT_APP_API_ROOT
const rootAthena = process.env.REACT_APP_ATHENA_API_ROOT
const CancelToken = axios.CancelToken;
//请求拦截器
axios.interceptors.request.use(config => {
    //发起请求时，取消掉当前正在进行的相同请求
    let requestName = config.method === 'post'?config.data.requestName :config.params.requestName
    //判断，如果这里拿到上一次的requestName，就取消上一次的请求
    if(requestName) {
        if(axios[requestName]&&axios[requestName].cancel){
            axios[requestName].cancel()
        }
        config.cancelToken = new CancelToken(c => {
            axios[requestName] = {}
            axios[requestName].cancel = c
        })
    }
    // if(config.method === 'post') {
    //   config.data = qs.stringify(config.data);
    // }
    return config
}, error => {
    return Promise.reject(error)
})

axios.defaults.timeout = 10000;
let flag = true;
//响应拦截器即异常处理
axios.interceptors.response.use(response => {
    console.log(response)
    if (response.data.httpCode === 500) {
        Notification.error({
            title: '错误',
            message: '对不起，你访问的信息迷路了，错误代码500'
        });
        return response
    } else if (response.data.httpCode === 401) {
        if (flag) {
            flag = false;
            // MessageBox.confirm('账号登录已过期或其它终端登录，请重新登录, 是否继续?', '账号异常', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            // }).then(() => {
            //     flag = true;
            //     router.push('/login');
            // }).catch(() => {
            //     MessageBox({
            //         type: 'info',
            //         message: '已取消,浏览更多内容，请登录后尝试'
            //     });
            //     flag = true;
            //     router.push('/login')
            // });
        }
    } else if (/^20\d/.test(response.data.httpCode)) {
        return response.data
    } else {
        // Notification.error({
        //     title: '错误',
        //     message: `对不起，你访问的信息迷路了`
        // });
        return response
    }
}, err => {
    console.log(err)
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                err.message = '错误请求'
                break;
            case 401:
                err.message = '未授权，请重新登录'
                // try{
                //     console.log(history)
                //     history.push('/login')
                // }catch(e){
                //     console.log(e)
                // }
                // history.push('/login')
                // window.location.href = './login'
                break;
            default:
                err.message = `连接错误${err.response.status}`
        }
      
    } else {
        if (err.code === 'ECONNABORTED' || err.message === 'Network Error') {
            // 请求超时
            var config = err.config;
            //如果配置不存在或重试属性未设置，抛出promise错误
            if (!config) return false
            //设置一个变量记录重新请求的次数
            console.log('重连次数', config.retryCount)
            config.retryCount = config.retryCount || 0;
            // 检查重新请求的次数是否超过我们设定的请求次数
            if (config.retryCount >= 3) {
                // Notification.error({
                //     title: '错误',
                //     message: '尝试重连后超时'
                // });
                return false
            }
            //重新请求的次数自增
            config.retryCount += 1;
            // 创建新的Promise来处理重新请求的间隙
            let backoff = new Promise((resolve) => {
                setTimeout(() => { resolve() }, 1000);
            });
            //返回axios的实体，重试请求
            return backoff.then(() => axios(config));

        } else {
            err.message = '服务器端出错'
           
        }
    }
    return Promise.reject(err)
})

export default {
    //get请求
    get(url, param, type = false) {
        if (type) {
            axios.defaults.baseURL = rootAthena
            axios.defaults.headers = {
                'Content-Type': 'application/json;charset=UTF-8',
                "ygwo_token": localStorage.getItem('token') || undefined,
                "token_type": 1
            }
        } else {
            axios.defaults.baseURL = root
            axios.defaults.headers = {
                'Content-Type': 'application/json;charset=UTF-8',
                "ygwo_token": localStorage.getItem('token') || undefined,
            }
        }
        return axios({
            method: 'get',
            url,
            params: param
        })
    },
    //post请求
    post(url, param, type = false) {
        if (type) {
            axios.defaults.baseURL = rootAthena
            axios.defaults.headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                "ygwo_token": localStorage.getItem('token') || undefined,
                "token_type": 1 
            }
        } else {
            axios.defaults.baseURL = root
            axios.defaults.headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                "ygwo_token": localStorage.getItem('token') || undefined,
            }
        }
        return axios({
            method: 'post',
            url,
            data: param,
            transformRequest: [function (data) {
                let ret = ''
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                return ret
            }]
        })
    },
    postForm(url, param, isAthena = false) {
        axios.defaults.baseURL = isAthena ? rootAthena : root
        return axios({
            method: 'POST',
            url,
            data: param,
            headers: {
                'Content-Type': 'multipart/form-data',
                "ygwo_token": localStorage.getItem('token') || undefined,
                "token_type": 1
            }
        })
    },
}

